package com.ITArmy.service.impl;

import com.ITArmy.beans.*;
import com.ITArmy.beans.Shows.ReadBlog;
import com.ITArmy.beans.Shows.UserMassage;
import com.ITArmy.common.ServerResponse;
import com.ITArmy.dao.*;
import com.ITArmy.service.BlogService;
import com.ITArmy.service.FocusService;
import com.ITArmy.service.TypeService;
import com.ITArmy.service.UserService;
import com.ITArmy.util.*;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    CheckTel checkTel = new CheckTel();
    isEmail checkEmail = new isEmail();
    SendEmail sendEmail = new SendEmail();
    GetUserSession getUserSession = new GetUserSession();
    DateChange dateChange = new DateChange();
    AddCookie addCookie = new AddCookie();
    private static Logger logger = Logger.getLogger(Controller.class);
    @Autowired
    CollectionsMapper collectionsMapper;
    @Autowired
    BlogMapper blogMapper;
    @Autowired
    SerializeMapper serializeMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    PraiseMapper praiseMapper;
    @Autowired
    TypeService typeService;
    @Autowired
    BlogService blogService;
    @Autowired
    FocusService focusService;
    @Autowired
    ConfigsMapper configsMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    FocusMapper focusMapper;

    isEmail check = new isEmail();

    /**
     * 添加用户
     */

    @Override
    public ServerResponse addUser(User user) {
        int resultCount = userMapper.insertSelective(user);
        CheckMessage check = new CheckMessage();
        return check.getMessage(resultCount, "添加成功", "添加失败");
    }

    /**
     * 注册用户
     */
    @Override
    public ServerResponse register(User user, HttpServletRequest req, String code) {
        System.out.println("输入的验证码为:" + code);
        if (check.isEmail(user.getuEmail()) != true) {
            return ServerResponse.createByErrorMesage("邮箱格式不正确...");
        }
        if (user == null) {
            return ServerResponse.createByErrorMesage("请填写完整的信息...");
        }
        //判断一下邮箱是否已经存在
        User findUser = userMapper.selectByEmail(user.getuEmail());
        if (findUser != null) {
            return ServerResponse.createByErrorMesage("您的邮箱已经注册过了....");
        }
        //判断一下验证码是否正确
        HttpSession codeSession = req.getSession();
        try {
            String backCode = (String) codeSession.getAttribute("code");
            if (!backCode.equals(code)) {
                return ServerResponse.createByErrorMesage("请输入正确的验证码...");
            }
            user.setCoId(1);
            int resultCount = userMapper.insertSelective(user);
            if (resultCount == 0) {
                return ServerResponse.createByErrorMesage("注册失败...");
            }
        } catch (Exception e) {
            return ServerResponse.createByErrorMesage("请先获取邮箱验证码...");
        }
        codeSession.removeAttribute("code");
        return ServerResponse.createBySuccessMessage("注册成功...");
    }

    /**
     * 获取用户的基本信息
     */
    @Override
    public ServerResponse getUser(HttpServletRequest req, Model model) {
        User user = getUserSession.getUser(req);
        if (user != null) {
            model.addAttribute("user", user);
            return ServerResponse.createBySuccess(model);
        } else {
            return ServerResponse.createByErrorMesage("用户没有登录，是否要登陆");
        }
    }

    /**
     * 查询一下是否已经注册
     */
    @Override
    public ServerResponse inquireEmail(String email) {
        if (email == null) {
            return ServerResponse.createByErrorMesage("请输入邮箱...");
        }
        if (check.isEmail(email) != true) {
            return ServerResponse.createByErrorMesage("邮箱格式不正确...");
        }
        if (userMapper.selectByEmail(email) != null) {
            return ServerResponse.createByErrorMesage("邮箱已存在...");
        } else {
            return ServerResponse.createBySuccessMessage("您的邮箱可以注册...");
        }
    }

    /**
     * 登录验证（管理员直接进入后台管理页面）
     */
    @Override
    public ServerResponse checkLogin(String uEmail, String uPwd, HttpServletRequest req, HttpServletResponse resp, boolean freeLogin, Model model) {
        Cookie[] cks = req.getCookies();
        HttpSession session = req.getSession();
        //进行验证cookie的存在及正确性
        if (cks != null) {
            String uId = "";
            for (Cookie c : cks) {
                if ("uId".equals(c.getName())) {// (如果)uid和cookie的名称相同
                    uId = c.getValue();
                    User user = userMapper.selectByPrimaryKey(Long.parseLong(uId));
                    Configs configs = configsMapper.selectByPrimaryKey(user.getCoId());
                    session.setAttribute("config", configs);
                    if ("1".equals(user.getuManage())) {
                        // 看看是否能查找到这个属性
                        session.setAttribute("user", user);
                        return ServerResponse.createBySuccess("ITArmy欢迎管理员登录...", 1);
                    } else {
                        session.setAttribute("user", user);
                        return ServerResponse.createBySuccess("ITArmy欢迎您...", 0);
                    }
                }
            }
        }
        if (uEmail == null || uPwd == null) {
            return ServerResponse.createByErrorMesage("邮箱,密码都不能为空...");
        }
        if (check.isEmail(uEmail) != true) {
            return ServerResponse.createByErrorMesage("邮箱格式不正确....");
        }
        User user = userMapper.findByEmail(uEmail, uPwd);
        if (user == null) {
            return ServerResponse.createByErrorMesage("密码错误...");
        }
        if (user != null) {
            //检验一下vip的到期时间，更新一下user的信息，
            session.setAttribute("user", user);
            userMapper.updateByPrimaryKeySelective(dateChange.CheckVipTime(user));
            //进行获取在线主题信息，然后储存到session中
            Configs configs = configsMapper.selectByPrimaryKey(user.getCoId());
            session.setAttribute("config", configs);
            //如果点击了七天免登陆则
            addCookie.addCookie(resp, user, freeLogin);
            if ("1".equals(user.getuManage())) {
                return ServerResponse.createBySuccess("ITArmy欢迎您...", 1);
            }
            return ServerResponse.createBySuccess("登陆成功...", 0);
        } else {
            return ServerResponse.createByErrorMesage("出现未知错误...");
        }
    }

    @Override
    /**修改用户的数据*/
    public ServerResponse updateUser(User user, HttpServletRequest request) {
        long uId = getUserSession.getUser(request).getuId();
        user.setuId(uId);
        //验证一下手机号的格式
        if (user.getuTel() != null) {
            if (checkTel.isPhone(user.getuTel())) {
                return ServerResponse.createByErrorMesage("请输入手机号...");
            }
        }
        int resultCount = userMapper.updateByPrimaryKeySelective(user);
        CheckMessage check = new CheckMessage();
        //更新一下session内的数据
        HttpSession session = request.getSession();
        session.setAttribute("user", userMapper.selectByPrimaryKey(uId));
        return check.getMessage(resultCount, "修改成功", "修改失败");
    }

    /**
     * 删除用户/用户自己清除自己的账号
     */
    @Override
    public ServerResponse deleteUser(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession userSession = req.getSession();
        User user = (User) userSession.getAttribute("user");
        int resultCount = userMapper.deleteByPrimaryKey(user.getuId());
        if (resultCount > 0) {
            userSession.removeAttribute("user");
            Cookie userCookie = new Cookie("uId", user.getuId() + "");// 因为uid是int类型的数据（变成字符串）
            // 设置Cookie的有效日期为7天
            userCookie.setMaxAge(0);
            // 设置有效路径
            userCookie.setPath("/");
            // 添加cookie信息
            resp.addCookie(userCookie);
            return ServerResponse.createBySuccess("注销成功...");
        }
        return ServerResponse.createByErrorMesage("注销失败...");
    }

    /**
     * 删除用户/用户自己清除自己的账号（可以批量删除,话说这个整合的不好写）（这里有一个bug===========================）
     */
    @Override
    public ServerResponse deleteUserByManager(long uId) {
        int resultCount = userMapper.deleteByPrimaryKey(uId);
        CheckMessage check = new CheckMessage();
        return check.getMessage(resultCount, "删除成功", "删除失败");

      /*  System.out.println("进行删除操作");
        ArrayList<Long> list = (ArrayList<Long>) object;
        if (list.size() > 1) {
            //进行批量删除
            int resultCount = 0;
            for (int i = 0; i < list.size() - 1; i++) {
                int Count = userMapper.deleteByPrimaryKey(list.get(i));
                resultCount += Count;
            }
            if (resultCount > 0) {
                return ServerResponse.createBySuccess("您一共删除" + resultCount + "个用户");
            }
            return ServerResponse.createByErrorMesage("删除失败...");
        }
        return ServerResponse.createByErrorMesage("请输入您要删除的用户id");*/
    }

    /**
     * 批量删除
     */
    @Override
    public ServerResponse deleteManyByIds(String[] ids) {
        int resultCount = userMapper.deleteManyByIds(ids);
        CheckMessage check = new CheckMessage();
        return check.getMessage(resultCount, "删除成功", "删除失败");
    }

    /**
     * （注销登录）
     */
    @Override
    public ServerResponse loginOut(HttpServletRequest req, HttpServletResponse resp) {
        //清除session和cookie
        HttpSession userSession = req.getSession();
        userSession.removeAttribute("user");
        Cookie userCookie = new Cookie("uId", "user");// 因为uid是int类型的数据（变成字符串）
        // 设置Cookie的有效日期为7天
        userCookie.setMaxAge(0);
        // 设置有效路径
        userCookie.setPath("/");
        // 添加cookie信息
        resp.addCookie(userCookie);
        return ServerResponse.createBySuccessMessage("注销成功...");
    }

    @Override
    public ServerResponse openVip(String email) {
        return null;
    }

    @Override
    public ServerResponse charge(double money) {
        return null;
    }

    /**
     * 用户回密码（先发验证码进行验证才能找密码找）
     */
    @Override
    public ServerResponse findPwd(String email) {
        if (!checkEmail.isEmail(email)) {
            return ServerResponse.createByErrorMesage("请输入正确的邮箱格式...");
        }
        User user = userMapper.selectByEmail(email);
        if (user == null) {
            return ServerResponse.createByErrorMesage("您的邮箱还没有注册过...");
        }
        //将密码发送到邮箱
        return sendEmail.sendEmailOther(email, "您的密码为:" + user.getuPwd());
    }

    //购买连载
    @Override
    public ServerResponse buySerialize(long serializeId) {
        return null;
    }


    //===============================
    @Override
    public void sikp(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.getRequestDispatcher("/WEB-INF/templates/blog.html").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public ServerResponse findUserById(long uId) {
        User user = userMapper.selectByPrimaryKey(uId);
        if (user == null) {
            return ServerResponse.createByErrorMesage("用户不存在...");
        }
        return ServerResponse.createBySuccess("查询成功...", user);
    }

    @Override
    public ServerResponse reduceGold(HttpServletRequest request, int amount) {
        return null;
    }

    /**
     * 进入个人主页的显示
     */
    @Override
    public UserMassage showPersonalMassage(HttpServletRequest request) {
        User user = getUserSession.getUser(request);
        UserMassage userMassage = new UserMassage();
        //获取用户的全部粉丝数量
        userMassage.setFun(focusMapper.fansCount(user.getuId()));
        //获取用户关注的作者
        userMassage.setFocus(focusMapper.focusCount(user.getuId()));
        //获取用户发表的文章数
        userMassage.setBlogNum(blogMapper.blogCount(user.getuId()));
        //获取用户的获赞量(评论，博客，回复，的点赞)
        userMassage.setPraiseNum(praiseMapper.praiseCount(user.getuId()));
        return userMassage;
    }

    //进入别人的主页进行参观
    @Override
    public UserMassage showOtherMassage(long uId) {
        User user =userMapper.selectByPrimaryKey(uId);
        UserMassage userMassage = new UserMassage();
        userMassage.setUser(user);
        //获取用户的全部粉丝数量
        userMassage.setFun(focusMapper.fansCount(user.getuId()));
        //获取用户关注的作者
        userMassage.setFocus(focusMapper.focusCount(user.getuId()));
        //获取用户发表的文章数
        userMassage.setBlogNum(blogMapper.blogCount(user.getuId()));
        //获取用户的获赞量(评论，博客，回复，的点赞)
        userMassage.setPraiseNum(praiseMapper.praiseCount(user.getuId()));
        return userMassage;
    }


    /**
     * 上传用户的头像
     */
    @Override
    public ServerResponse uploadHead(MultipartFile uHeaed, HttpServletRequest req) {
        User user = getUserSession.getUser(req);
        String path = "/static/uploads/userHead/";
        UploadPicture uploadPicture = new UploadPicture();
        user.setuHead((String) uploadPicture.upload(uHeaed, req, path).getData());
        System.out.println("头像路++++++" + user.getuHead());
        int resultCount = userMapper.updateByPrimaryKeySelective(user);
        if (resultCount > 0) {
            return ServerResponse.createByErrorMesage("上传成功...");
        }
        return ServerResponse.createByErrorMesage("上传成功...");
    }

    /**
     * 进入主页面
     */
    @Override
    public void goIndexPage(HttpServletRequest request, HttpServletResponse response, Model model) {
        getUserSession.addUserModel(request, model);
        ServerResponse typeServerResponse = typeService.typeList();
        model.addAttribute("allBlogType", typeServerResponse.getData());
        //获取推荐的博客(当前最新的 6篇)
        List<Blog> blogs = blogMapper.recommentTenBlog();
        List<ReadBlog> recommendBlog = new ArrayList();
        for (int i = 0; i < blogs.size(); i++) {
            ReadBlog readBlog = new ReadBlog();
            //博客信息
            readBlog.setBlog(blogs.get(i));
            //用户信息
            readBlog.setUser(userMapper.selectByPrimaryKey(blogs.get(i).getuId()));
            //点赞数量
            readBlog.setLikeNumber(praiseMapper.selectBlogPraiseCount(blogs.get(i).getbId()).size());
            //评论数量
            readBlog.setCommentNumber(commentMapper.findCommentByBlogId(blogs.get(i).getbId()).size());
            recommendBlog.add(readBlog);
        }

        model.addAttribute("recommendBlog", recommendBlog);
    }

    @Override
    /**进入后台页面*/
    public void goBackPage(HttpServletRequest request, HttpServletResponse response, int page, Model model) {
        getUserSession.addUserModel(request, model);
        // List<Blog> blogs = blogService.findAllBlog();
        PageHelper.startPage(page, 10);
        List<Blog> blogs = blogService.findAllBlog();
        PageInfo<Blog> blogPageInfo = new PageInfo<>(blogs, 15);
        model.addAttribute("blogList", blogPageInfo);
        //model.addAttribute("blogList", blogs);
    }
    //用户点赞连载

    //测试根据用户的id进行查询用户的信息

    //遍历用户信息

    @Override
    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }

    //查询所有的博客信息，进行延时加载


}
